<template>
  <div class="xx">
    <h1 class="title">登录</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button class="check" @click="$emit('toRegister')">切换到注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from "@/api/user";
import { success, info } from "@/utils";
import { mapMutations, mapState } from "vuex";
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名" }],
        password: [{ required: true, message: "请输入密码" }],
      },
    };
  },
  computed: {
    ...mapState(['info'])
  },
  methods: {
    ...mapMutations(["setInfo"]),
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await login({ ...this.ruleForm });
          // 登录成功
          if (res.code === 1) {
            success("登录成功");
            this.resetForm("ruleForm");
            // 存到store
            this.setInfo(res.data);

            const path = this.info.role === 'tch' ? 'tchIndex' : 'stuIndex'
            this.$router.push('/' + path)
          } else {
            info(res.msg);
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>


<style scoped>
.title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0;
}

input {
  width: 200px;
}
</style>